package com.archway.appframe.config;

import com.archway.appframe.config.cache.Cache;
import com.archway.appframe.config.cache.CacheSapce;
import com.archway.appframe.config.defaults.Property;

import java.io.InputStream;

import org.apache.commons.digester3.Digester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConfigHelper {
	private transient static Logger log = LoggerFactory.getLogger(ConfigHelper.class);

	//private static ConfigHelper instance = null;

//  private static Defaults defaults = null;
//  private static Service[] services = null;
//  private static Dao[] daos = null;
	private static CacheSapce caches = null;

	//private static Boolean isInit = Boolean.FALSE;

	// private static Boolean isServiceInit = Boolean.FALSE;
	// private static Boolean isDaoInit = Boolean.FALSE;
	private static Boolean isCacheInit = Boolean.FALSE;

//  public static ConfigHelper getInstance()
//    throws Exception
//  {
//    if (isInit.equals(Boolean.FALSE)) {
//      synchronized (isInit) {
//        if (isInit.equals(Boolean.FALSE)) {
//          //defaults = createDefaults();
//
//          isInit = Boolean.TRUE;
//        }
//      }
//      instance = new ConfigHelper();
//    }
//    return instance;
//  }
//
//  public Defaults getDefaults()
//  {
//    return defaults;
//  }
//
//  public Service[] getServices()
//  {
//    if (services == null) {
//      synchronized (isServiceInit) {
//        if (isServiceInit.equals(Boolean.FALSE)) {
//          try {
//            services = createServices();
//            isServiceInit = Boolean.TRUE;
//          }
//          catch (Throwable ex) {
//            throw new RuntimeException(ex);
//          }
//        }
//      }
//    }
//    return services;
//  }
//
//  public Dao[] getDaos()
//  {
//    if (daos == null) {
//      synchronized (isDaoInit) {
//        if (isDaoInit.equals(Boolean.FALSE)) {
//          try {
//            daos = createDaos();
//            isDaoInit = Boolean.TRUE;
//          }
//          catch (Throwable ex) {
//            throw new RuntimeException(ex);
//          }
//        }
//      }
//    }
//    return daos;
//  }

	public static CacheSapce getCacheInstance() throws ConfigException {
		if (caches == null) {
			synchronized (isCacheInit) {
				if (isCacheInit.equals(Boolean.FALSE)) {
					caches = new ConfigHelper().createCacheGroup();
					isCacheInit = Boolean.TRUE;
				}
			}
		}
		return caches;
	}
	
	private CacheSapce createCacheGroup() throws ConfigException {
		CacheSapce cacheSapce = null;
		String cacheFileName = "config/cache/cache.xml";
		InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(cacheFileName);
		if (input == null) {
			log.error(cacheFileName + "配置文件获取失败！");
			throw new ConfigException(cacheFileName + "配置文件获取失败！");
		}
		Digester digester = new Digester();

		digester.setValidating(false); // 不验证dtd
		// 初次遇到时创建
		digester.addObjectCreate("cacheSapce", CacheSapce.class.getName());
		digester.addSetProperties("cacheSapce");
		// 初次遇到时创建
		digester.addObjectCreate("cacheSapce/cache", Cache.class.getName());
		digester.addSetProperties("cacheSapce/cache");
		// 再次遇到时添加到节点下
		digester.addSetNext("cacheSapce/cache", "addCache", Cache.class.getName());// addCache方法来自于CacheGroup

		digester.addObjectCreate("cacheSapce/cache/property", Property.class.getName());
		digester.addSetProperties("cacheSapce/cache/property");
		digester.addSetNext("cacheSapce/cache/property", "addProperty", Property.class.getName());

		try {
			cacheSapce = (CacheSapce) digester.parse(input);
		} catch (Exception e) {
			log.error(cacheFileName + "配置文件配置有误！", e);
			throw new ConfigException(cacheFileName + "配置文件配置有误！");
		}
		return cacheSapce;
	}
//  private static Defaults createDefaults()
//    throws Exception
//  {
//    Defaults rtn = null;
//
//    String defaultsFileName = "system/service/defaults.xml";
//    if (!(StringUtils.isBlank(System.getProperty("appframe.service.default.filename")))) {
//      defaultsFileName = System.getProperty("appframe.service.default.filename").trim();
//      System.out.println("Use defaults.xml:" + defaultsFileName);
//    }
//
//    InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(defaultsFileName);
//
//    if (input == null)
//    {
//      //String msg = AppframeLocaleFactory.getResource("com.ai.appframe2.complex.xml.no_config_file", new String[] { defaultsFileName });
//
//      //throw new Exception(msg);
//    }
//
//    Digester digester = new Digester();
//
//    digester.setValidating(false);
//    digester.addObjectCreate("defaults", Defaults.class.getName());
//    digester.addSetProperties("defaults");
//
//    digester.addObjectCreate("defaults/center", Center.class.getName());
//    digester.addSetProperties("defaults/center");
//
//    digester.addObjectCreate("defaults/center/property", Property.class.getName());
//    digester.addSetProperties("defaults/center/property");
//
//    digester.addObjectCreate("defaults/interceptor", Interceptor.class.getName());
//    digester.addSetProperties("defaults/interceptor");
//
//    digester.addObjectCreate("defaults/interceptor/clazz", Clazz.class.getName());
//    digester.addSetProperties("defaults/interceptor/clazz");
//
//    digester.addObjectCreate("defaults/interceptor/clazz/property", Property.class.getName());
//    digester.addSetProperties("defaults/interceptor/clazz/property");
//
//    digester.addObjectCreate("defaults/proxy", Proxy.class.getName());
//    digester.addSetProperties("defaults/proxy");
//
//    digester.addObjectCreate("defaults/proxy/clazz", Clazz.class.getName());
//    digester.addSetProperties("defaults/proxy/clazz");
//
//    digester.addObjectCreate("defaults/proxy/clazz/property", Property.class.getName());
//    digester.addSetProperties("defaults/proxy/clazz/property");
//
//    digester.addObjectCreate("defaults/proxy/env", Env.class.getName());
//    digester.addSetProperties("defaults/proxy/env");
//
//    digester.addObjectCreate("defaults/proxy/env/property", Property.class.getName());
//    digester.addSetProperties("defaults/proxy/env/property");
//
//    digester.addObjectCreate("defaults/transaction", Transaction.class.getName());
//    digester.addSetProperties("defaults/transaction");
//
//    digester.addObjectCreate("defaults/transaction/clazz", Clazz.class.getName());
//    digester.addSetProperties("defaults/transaction/clazz");
//
//    digester.addObjectCreate("defaults/transaction/listener", Listener.class.getName());
//    digester.addSetProperties("defaults/transaction/listener");
//
//    digester.addObjectCreate("defaults/transaction/clazz/property", Property.class.getName());
//    digester.addSetProperties("defaults/transaction/clazz/property");
//
//    digester.addObjectCreate("defaults/transaction/mapping", Mapping.class.getName());
//    digester.addSetProperties("defaults/transaction/mapping");
//
//    digester.addObjectCreate("defaults/transaction/mapping/property", Property.class.getName());
//    digester.addSetProperties("defaults/transaction/mapping/property");
//
//    digester.addObjectCreate("defaults/datasource", DataSource.class.getName());
//    digester.addSetProperties("defaults/datasource");
//
//    digester.addObjectCreate("defaults/datasource/clazz", Clazz.class.getName());
//    digester.addSetProperties("defaults/datasource/clazz");
//
//    digester.addObjectCreate("defaults/datasource/clazz/property", Property.class.getName());
//    digester.addSetProperties("defaults/datasource/clazz/property");
//
//    digester.addObjectCreate("defaults/datasource/pool", Pool.class.getName());
//    digester.addSetProperties("defaults/datasource/pool");
//
//    digester.addObjectCreate("defaults/datasource/pool/property", Property.class.getName());
//    digester.addSetProperties("defaults/datasource/pool/property");
//
//    digester.addObjectCreate("defaults/datasource/mapping", Mapping.class.getName());
//    digester.addSetProperties("defaults/datasource/mapping");
//
//    digester.addObjectCreate("defaults/datasource/mapping/property", Property.class.getName());
//    digester.addSetProperties("defaults/datasource/mapping/property");
//
//    digester.addObjectCreate("defaults/include", Include.class.getName());
//    digester.addSetProperties("defaults/include");
//
//    digester.addObjectCreate("defaults/load-on-startup", LoadOnStartup.class.getName());
//    digester.addSetProperties("defaults/load-on-startup");
//    digester.addObjectCreate("defaults/load-on-startup/startup-class", StartupClass.class.getName());
//    digester.addSetProperties("defaults/load-on-startup/startup-class");
//
//    digester.addSetNext("defaults/center", "setCenter", Center.class.getName());
//    digester.addSetNext("defaults/proxy", "setProxy", Proxy.class.getName());
//    digester.addSetNext("defaults/transaction", "setTransaction", Transaction.class.getName());
//    digester.addSetNext("defaults/datasource", "setDatasource", DataSource.class.getName());
//    digester.addSetNext("defaults/include", "addInclude", Include.class.getName());
//
//    digester.addSetNext("defaults/center/property", "addProperty", Property.class.getName());
//
//    digester.addSetNext("defaults/interceptor", "setInterceptor", Interceptor.class.getName());
//    digester.addSetNext("defaults/interceptor/clazz", "addClazz", Clazz.class.getName());
//    digester.addSetNext("defaults/interceptor/clazz/property", "addProperty", Property.class.getName());
//
//    digester.addSetNext("defaults/proxy/clazz", "setClazz", Clazz.class.getName());
//    digester.addSetNext("defaults/proxy/clazz/property", "addProperty", Property.class.getName());
//    digester.addSetNext("defaults/proxy/env", "addEnv", Env.class.getName());
//    digester.addSetNext("defaults/proxy/env/property", "addProperty", Property.class.getName());
//
//    digester.addSetNext("defaults/transaction/clazz", "setClazz", Clazz.class.getName());
//
//    digester.addSetNext("defaults/transaction/clazz/property", "addProperty", Property.class.getName());
//    digester.addSetNext("defaults/transaction/listener", "addListener", Listener.class.getName());
//    digester.addSetNext("defaults/transaction/mapping", "setMapping", Mapping.class.getName());
//    digester.addSetNext("defaults/transaction/mapping/property", "addProperty", Property.class.getName());
//
//    digester.addSetNext("defaults/datasource/clazz", "setClazz", Clazz.class.getName());
//    digester.addSetNext("defaults/datasource/clazz/property", "addProperty", Property.class.getName());
//    digester.addSetNext("defaults/datasource/pool", "addPool", Pool.class.getName());
//    digester.addSetNext("defaults/datasource/pool/property", "addProperty", Property.class.getName());
//    digester.addSetNext("defaults/datasource/mapping", "setMapping", Mapping.class.getName());
//    digester.addSetNext("defaults/datasource/mapping/property", "addProperty", Property.class.getName());
//
//    digester.addSetNext("defaults/load-on-startup", "setLoadOnStartup", LoadOnStartup.class.getName());
//    digester.addSetNext("defaults/load-on-startup/startup-class", "addStartupClass", StartupClass.class.getName());
//
//    rtn = (Defaults)digester.parse(input);
//    return rtn;
//  }

//  private static Service[] createServices()
//    throws Exception
//  {
//    HashMap serviceMap = new HashMap();
//    Include[] includes = defaults.getIncludes();
//    for (int i = 0; i < includes.length; ++i) {
//      if (includes[i].getType().equalsIgnoreCase("sv")) {
//        Services services = null;
//        InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(includes[i].getClasspath());
//
//        if (input == null)
//        {
//          throw new Exception(AppframeLocaleFactory.getResource("com.ai.appframe2.complex.xml.no_config_file", new String[] { includes[i].getClasspath() }));
//        }
//
//        Digester digester = new Digester();
//
//        digester.setValidating(false);
//        digester.addObjectCreate("services", Services.class.getName());
//        digester.addSetProperties("services");
//
//        digester.addObjectCreate("services/service", Service.class.getName());
//        digester.addSetProperties("services/service");
//
//        digester.addObjectCreate("services/service/property", Property.class.getName());
//        digester.addSetProperties("services/service/property");
//
//        digester.addObjectCreate("services/service/property/ref", Ref.class.getName());
//        digester.addSetProperties("services/service/property/ref");
//
//        digester.addObjectCreate("services/service/tx", Tx.class.getName());
//        digester.addSetProperties("services/service/tx");
//
//        digester.addObjectCreate("services/service/tx/method", Method.class.getName());
//        digester.addSetProperties("services/service/tx/method");
//
//        digester.addSetNext("services/service", "addService", Service.class.getName());
//        digester.addSetNext("services/service/property", "addProperty", Property.class.getName());
//        digester.addSetNext("services/service/property/ref", "setRef", Ref.class.getName());
//        digester.addSetNext("services/service/tx", "setTx", Tx.class.getName());
//        digester.addSetNext("services/service/tx/method", "addMethod", Method.class.getName());
//
//        services = (Services)digester.parse(input);
//
//        Service[] objService = services.getServices();
//        for (int j = 0; j < objService.length; ++j) {
//          if (serviceMap.containsKey(objService[j].getId()))
//          {
//            throw new Exception(AppframeLocaleFactory.getResource("com.ai.appframe2.complex.xml.SV_double_define", new String[] { objService[j].getId() }));
//          }
//
//          serviceMap.put(objService[j].getId(), objService[j]);
//        }
//      }
//
//    }
//
//    List rtn = new ArrayList();
//    Collection c = serviceMap.values();
//    for (Iterator iter = c.iterator(); iter.hasNext(); ) {
//      Service item = (Service)iter.next();
//      rtn.add(item);
//    }
//
//    return ((Service[])(Service[])rtn.toArray(new Service[0]));
//  }

//  private static Dao[] createDaos()
//    throws Exception
//  {
//    HashMap daoMap = new HashMap();
//    Include[] includes = defaults.getIncludes();
//    for (int i = 0; i < includes.length; ++i) {
//      if (includes[i].getType().equalsIgnoreCase("dao")) {
//        Daos objDaos = null;
//        InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(includes[i].getClasspath());
//
//        if (input == null)
//        {
//          throw new Exception(AppframeLocaleFactory.getResource("com.ai.appframe2.complex.xml.no_config_file", new String[] { includes[i].getClasspath() }));
//        }
//
//        Digester digester = new Digester();
//
//        digester.setValidating(false);
//        digester.addObjectCreate("daos", Daos.class.getName());
//        digester.addSetProperties("daos");
//
//        digester.addObjectCreate("daos/dao", Dao.class.getName());
//        digester.addSetProperties("daos/dao");
//
//        digester.addObjectCreate("daos/dao/property", Property.class.getName());
//        digester.addSetProperties("daos/dao/property");
//
//        digester.addSetNext("daos/dao", "addDao", Dao.class.getName());
//        digester.addSetNext("daos/dao/property", "addProperty", Property.class.getName());
//
//        objDaos = (Daos)digester.parse(input);
//
//        Dao[] objDao = objDaos.getDaos();
//        for (int j = 0; j < objDao.length; ++j) {
//          if (daoMap.containsKey(objDao[j].getId()))
//          {
//            throw new Exception(AppframeLocaleFactory.getResource("com.ai.appframe2.complex.xml.DAO_double_define", new String[] { objDao[j].getId() }));
//          }
//
//          daoMap.put(objDao[j].getId(), objDao[j]);
//        }
//      }
//
//    }
//
//    List rtn = new ArrayList();
//    Collection c = daoMap.values();
//    for (Iterator iter = c.iterator(); iter.hasNext(); ) {
//      Dao item = (Dao)iter.next();
//      rtn.add(item);
//    }
//
//    return ((Dao[])(Dao[])rtn.toArray(new Dao[0]));
//  }



  
  
	public static void main(String[] args) throws ConfigException {
		Cache[] caches = getCacheInstance().getCaches();
		for (Cache cache : caches) {
			System.out.println(cache.getId());
			for (Property property : cache.getPropertys()) {
				System.out.println(property.getName());
			}
		}
	}
  
  
  
  
  
  
  
  
  
//  public static void main2(String[] args) throws Exception {
//    Env[] env = getInstance().getDefaults().getProxy().getEnvs();
//    for (int i = 0; i < env.length; ++i) {
//      System.out.println(env[i].getProperties()[0].getName());
//      System.out.println(env[i].getProperties().length);
//    }
//
//    System.out.println(getInstance().getDefaults().getProxy().getClazz().getName());
//  }
//
//  public static void main(String[] args) throws Exception {
//    getInstance().getDefaults();
//    long start = System.currentTimeMillis();
//    Defaults defaults = getInstance().getDefaults();
//
//    System.out.println(defaults.getCenter().getProperties().length);
//    System.out.println("8888888888888888888888888888888");
//    Pool[] p = defaults.getDatasource().getPools();
//    for (int i = 0; i < p.length; ++i) {
//      Property[] pa = p[i].getProperties();
//      for (int j = 0; j < pa.length; ++j) {
//        System.out.println(pa[j].getName() + ":" + pa[j].getValue());
//      }
//      System.out.println("=======================");
//    }
//    System.out.println("Time cost:" + (System.currentTimeMillis() - start) + ":ms");
//
//    Service[] s = getInstance().getServices();
//    s = getInstance().getServices();
//    for (int i = 0; i < s.length; ++i) {
//      System.out.println(s[i].getId());
//    }
//
//    System.out.println("******************************");
//    Dao[] a = getInstance().getDaos();
//    for (int i = 0; i < a.length; ++i) {
//      System.out.println(a[i].getId());
//    }
//
//    System.out.println("******************************");
//    LoadOnStartup startup = getInstance().getDefaults().getLoadOnStartup();
//    if (startup != null) {
//      StartupClass[] startClass = startup.getStartupClasss();
//      for (int i = 0; i < startClass.length; ++i) {
//        System.out.println(startClass[i].getName() + "=" + startClass[i].getAsyn());
//        String asyn = startClass[i].getAsyn();
//        if ((!(StringUtils.isBlank(asyn))) && (((asyn.trim().equalsIgnoreCase("1")) || (asyn.trim().equalsIgnoreCase("true"))))) {
//          System.out.println("111111111");
//        }
//        else
//          System.out.println("222222222");
//      }
//    }
//  }
}